const UserModel = require("../model/addCart");
const jwt = require("jsonwebtoken");
const {
    secret
} = require("../config");
const catchError = require("../utils/catchError");
const {
    deleteMany
} = require("../model/addCart");

class Cart {
    async addCart(ctx) {
        let {
            username,
            cartName,
            cartDes,
            cartImg,
            cartType,
            cartPrice,
            cartSpc,
            cartNum,
        } = ctx.request.body;

        let user = await UserModel.findOne({
            cartName
        });
        if (user) {
            // console.log(user.cartNum);
            cartNum = user.cartNum + cartNum
            console.log(cartNum);
            user = await UserModel.findOneAndUpdate({cartName}, {cartNum});

            return ctx.body = {
                code: 1,
                msg: "增加成功",
            };
        }


        let data = await UserModel.create({
            username,
            cartName,
            cartDes,
            cartImg,
            cartType,
            cartPrice,
            cartSpc,
            cartNum,
        });
        ctx.body = {
            code: 0,
            msg: "添加成功",
        };
    }

    async getCart(ctx) {
        let {
            username
        } = ctx.request.body;
        let user = await UserModel.find({
            username
        })
        console.log(user);
        ctx.body = {
            code: 0,
            msg: "获取成功",
            data: {
                ...user
            }
        };
    }
    async deleteCart(ctx) {
        let {
            _id
        } = ctx.request.body;

        let idArr = _id.split(',')
        console.log(idArr);
        await UserModel.deleteMany({
            _id: {
                $in: idArr
            }
        })


        ctx.body = {
            code: 0,
            msg: "删除成功",
        };
    }
}

module.exports = new Cart();